import {
    fetch,
    fetchOne,
    DeleceGateway,
    AddGateway,
    FetchUser,
    FetchOneGateway,
    UpdateGaeteway
} from './service';
  
const Model = {
    namespace: 'gateway',
    state: {
        
    },

    effects: {
        *fetch({ payload }, { call }) {
            const response = yield call(fetch, payload);
            if (!response.List) {
                return { status: 500 }
            }

            const data = []
            response.List.map(item =>{
                data.push({
                    key: item.Id,
                    id: item.Id,
                    Users: item.Users,
                    name: item.Code,
                    currentAckTime: item.AckTime,
                    latestAckTime: null,
                    latestMessageTime: null,
                    status: !item.Dacl,
                })
                return 200
            })
            return {
                status: 200,
                totalPageSize: response.Page.TotalCount,
                data,
            }
        },

        // delete gateway
        *daclGateway({ payload }, { call }) {
            const idObj = {Id: payload.id}
            const response = yield call(fetchOne, idObj)
            const data = {
                ...response[0],
                Dacl: response[0].Dacl ? 0 : 1
            }
            const res = yield call(UpdateGaeteway, data)
            if (res) { return {status: 200, data: res}  }
            return {status: 500, data: res}
        },

        *deleceGateway({ payload }, { call }) {
            const response = yield call(DeleceGateway, payload)
            return {status: 200, data: response}
        },

        *addGateway({ payload }, { call }) {
            const data = {
                Code: payload.imei
            }
            const response = yield call(AddGateway, data)
            return {status: 200, data: response}
        },

        *fetchUser(_, { call }) {
            const response = yield call(FetchUser)
            const data = []
            if (response && response.length > 0) {
                response.map(item =>{
                    data.push({
                        ...item,
                        key: item.Id
                    })
                    return 200
                })
            }
            return {status: 200, data}
        },
        
        *fetchOneGateway({ payload }, { call }) {
            const { select } = payload
            const userList = []
            select.map(item =>{
                userList.push({Id: item})
                return 200
            })
            const response = yield call(FetchOneGateway, payload)
            const data = {
                ...response[0],
                Users: userList
            }
            const res = yield call(UpdateGaeteway, data)
            return {status: 200, data: res}
        }

    },

    reducers: {
        
    },
}
export default Model;
  